package cn.yqm.modules.service;

import cn.hutool.core.util.RandomUtil;
import cn.yqm.common.UploadInterface;
import cn.yqm.common.YqmProperties;
import cn.yqm.common.enums.YqmUploadEnum;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 本地上传存储
 *
 * @author weiximei
 * @domain www.yqmshop.cn
 * @since 2023/8/20
 */
@Slf4j
@AllArgsConstructor
@Component
public class LocalUploadImpl implements UploadInterface {

    private final YqmProperties yqmProperties;

    @Override
    public String uploadType() {
        return YqmUploadEnum.LOCAL.getValue();
    }

    @Override
    public String upload(byte[] bytes, String originFileName) {
        String path = yqmProperties.getFileUploadPath();
        // 获取文件后缀
        String suffix = originFileName.substring(originFileName.lastIndexOf("."));
        String fileName = generateFileName() + suffix;
        this.storeFileWithFileName(bytes, path, fileName);
        log.debug("上传文件的位置: {} 文件名: {}", path, fileName);
        return yqmProperties.getOpenFileServerUrl() + fileName;
    }

    public void storeFileWithFileName(byte[] content, String path, String fileName) {
        // 目录不存在则创建
        java.io.File file = new java.io.File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        try (FileOutputStream os = new FileOutputStream(path + fileName);
             ByteArrayInputStream is = new ByteArrayInputStream(content)) {
            IOUtils.copy(is, os);
        } catch (IOException e) {
            log.error("存储文件到本地时发生异常：{}", e);
        }
    }

    private String generateFileName() {
        return System.currentTimeMillis() + "_" + RandomUtil.randomNumbers(6);
    }
}
